package com.flower.wholesale.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.flower.wholesale.enu.RedisKeyEnum;
import com.flower.wholesale.util.CaptchaUtil;
import com.flower.wholesale.util.CookiesUtil;
import com.flower.wholesale.util.RedisUtil;

/** 
 * @author: 姚雁飞
 * @desc: 图片验证码
 * @date: 2020年1月16日 下午3:46:46
 * @since JDK1.8 
 * @see com.flower.wholesale.controller
 */
@RestController
@RequestMapping("/imagecode")
public class ImageCodeController {
	
	@Autowired
	private RedisUtil redisUtil;
	private static String simpleCaptcha = "verificationCode";
	
	/**
     * 用于生成带四位数字验证码的图片
     */
    @GetMapping("/getCode")
    @ResponseBody
    public String imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        OutputStream os = response.getOutputStream();
        //返回验证码和图片的map
        Map<String,Object> map = CaptchaUtil.getImageCode(86, 37, os);
        //验证码存入缓存中，有效期一分钟
        String uuid = UUID.randomUUID().toString();
        redisUtil.set(RedisKeyEnum.VERIFICATION_CODE.getKey()+uuid, map.get("strEnsure").toString().toLowerCase(),60);
        CookiesUtil.setCookie(response, simpleCaptcha, uuid, 60);
//        request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString().toLowerCase());
//        request.getSession().setAttribute("codeTime",new Date().getTime());
        
        try {
            ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
        } catch (IOException e) {
            return "";
        }   finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        return null;
    }
    /**
     * 
     * @author: 姚雁飞
     * @desc: 校验验证码是否正确
     * @date: 2020年1月16日 下午4:08:56
     * @param request
     * @param session
     * @param checkCode 验证码
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/verify")
    @ResponseBody
    public String checkcode(HttpServletRequest request,
                            HttpSession session,
                            String checkCode) throws Exception {
        // 验证码有效时长为1分钟
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");
        // 获得验证码对象
        Object cko = session.getAttribute(simpleCaptcha);
        if (cko == null) {
            request.setAttribute("errorMsg", "请输入验证码！");
            return "请输入验证码！";
        }
        String captcha = cko.toString();
        // 判断验证码输入是否正确
        if (StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode.equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "验证码错误，请重新输入！";
        } else if ((now.getTime() - codeTime) / 1000 / 60 > 1) {
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        } else {

            // 在这里可以处理自己需要的事务，比如验证登陆等

            return "验证通过！";
        }
    }

}
